﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Entity.Goods;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business
{
    public class BTB_CommentBusiness : BaseBusiness<BTB_Comment>, IBTB_CommentBusiness, ITransientDependency
    {
        private readonly IOperator _Operator;
        public BTB_CommentBusiness(IDbAccessor db, IOperator Operators)
            : base(db)
        {
            _Operator = Operators;
        }

        #region 外部接口

        public async Task<PageResult<BTB_Comment>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<BTB_Comment>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<BTB_Comment, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<BTB_Comment> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(BTB_Comment data)
        {
            if (data.Product_Id.IsNullOrEmpty())
            {
                data.Product_Id = data.decimalId;
            }

            var res = await Db.GetIQueryable<Order_Decimal>().SingleOrDefaultAsync(p => p.Id == data.decimalId);
            if (res!=null)
            {
                res.DATA0 = "1";
                await Db.UpdateAsync(res);


                int sCount = Db.GetIQueryable<Order_Decimal>().Where(x => x.OrderMaster_Id.Equals(res.OrderMaster_Id)).Count();
                int fCount = Db.GetIQueryable<Order_Decimal>().Where(x => x.OrderMaster_Id.Equals(res.OrderMaster_Id) && x.DATA0.Equals("1")).Count();
                if (sCount == fCount)
                {
                    await Db.UpdateAsync<Order_Master>(x=>x.Id.Equals(res.OrderMaster_Id),y=> y.IsDiscuss = true);
                }

                await InsertAsync(data);
            }
        }



           


           

        public async Task UpdateDataAsync(BTB_Comment data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<PageResult<BTB_CommentdTO>> GetDataForeListAsync(PageInput<BTB_Comment> input)
        {
            var put = input.Search;
            var q = Db.GetIQueryable<BTB_Comment>().Where(t => true);
            if (!string.IsNullOrWhiteSpace(put.Id))
            {
                q = q.Where(t => t.Parent_Id.Equals(put.Id));
            }
            if (!string.IsNullOrWhiteSpace(put.Product_Id))
            {
                q = q.Where(t => t.Product_Id.Equals(put.Product_Id));
            }
            if (put.State != null)
            {
                q = q.Where(t => t.State.Equals(put.State));
            }
            if (!put.Comment_Content.IsNullOrEmpty())
            {
                q = q.Where(t => t.Comment_Content.Contains(put.Comment_Content));
            }
            var count = q.ToList().Count;

            var p = await q.OrderBy(t => t.CreateTime).Select(t => new BTB_CommentdTO
            {
                Id = t.Id,
                CreateTime = t.CreateTime,
                Comment_Content = t.Comment_Content,
                _StaffUsers = Db.GetIQueryable<BTB_StaffUser>(true).Where(s => s.id.Equals(t.CreatorId)).Select(s => new BTB_StaffUserDtoTwo { Sex = s.Sex, HeadPortrait = t.IsNickName? "" : s.HeadPortrait, id = s.id, NickName = t.IsNickName ? "匿名用户" : s.NickName }).FirstOrDefault(),
                // CreteName = Db.GetIQueryable<BTB_StaffUser>(true).SingleOrDefault(s => s.id.Equals(t.CreatorId)).NickName,
                Parent_Id = t.Parent_Id,
                Product = Db.GetIQueryable<Order_Decimal>(true).SingleOrDefault(k => k.Id.Equals(t.Product_Id)),
                State = t.State,
                Top_Status = t.Top_Status,
                Comment_Flag = t.Comment_Flag,
                Comment_State = t.Comment_State,
                Comment_Image = t.Comment_Image,
                Orderbys = t.Orderbys
            }).OrderByDescending(x => x.CreateTime).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            //p.ForEach(s => s._CommentdTOs = GetComment(null, p));

            var DATAS = GetComment(null, p);

            return new PageResult<BTB_CommentdTO> { Data = DATAS, Total = count };
        }

        public async Task<PageResult<BTB_CommentdTO>> GetDataTwoListAsync(PageInput<BTB_Comment> input)
        {
            var put = input.Search;
            var q = Db.GetIQueryable<BTB_Comment>().Where(t => t.Product_Id.Equals(put.Product_Id));
            if (!string.IsNullOrWhiteSpace(put.Id))
            {
                q = q.Where(t => t.Parent_Id.Equals(put.Id));
            }
            if (put.State != null)
            {
                q = q.Where(t => t.State.Equals(put.State));
            }
            if (!put.Comment_Content.IsNullOrEmpty())
            {
                q = q.Where(t => t.Comment_Content.Contains(put.Comment_Content));
            }
            var count = q.ToList().Count;

            var p = await q.OrderBy(t => t.CreateTime).Select(t => new BTB_CommentdTO
            {
                Id = t.Id,
                CreateTime = t.CreateTime,
                Comment_Content = t.Comment_Content,
                _StaffUsers = Db.GetIQueryable<BTB_StaffUser>(true).Where(s => s.id.Equals(t.CreatorId)).Select(s => new BTB_StaffUserDtoTwo { Sex = s.Sex, HeadPortrait = s.HeadPortrait, id = s.id, NickName = s.NickName }).FirstOrDefault(),
                // CreteName = Db.GetIQueryable<BTB_StaffUser>(true).SingleOrDefault(s => s.id.Equals(t.CreatorId)).NickName,
                Parent_Id = t.Parent_Id,
                Product = Db.GetIQueryable<Order_Decimal>(true).SingleOrDefault(k => k.Id.Equals(t.Product_Id)),
                State = t.State,
                Top_Status = t.Top_Status,
                Comment_Flag = t.Comment_Flag,
                Comment_State = t.Comment_State,
                Comment_Image = t.Comment_Image,
                Orderbys = t.Orderbys
            }).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            //p.ForEach(s => s._CommentdTOs = GetComment(null, p));

            var DATAS = GetComment(null, p);

            //var ps = await q.OrderBy(t => t.CreateTime).Select(t => new BTB_CommentdTO
            //{
            //    Id = t.Id,
            //    CreateTime = t.CreateTime,
            //    Comment_Content = t.Comment_Content,
            //    CreteName = Db.GetIQueryable<BTB_StaffUser>(true).SingleOrDefault(s => s.id.Equals(t.CreatorId)).NickName,
            //    Parent_Id = t.Parent_Id,
            //    ProductName = Db.GetIQueryable<BTB_Goods>(true).SingleOrDefault(k => k.ID.Equals(t.Product_Id)).GoodsName,
            //    State = t.State,
            //    Top_Status = t.Top_Status,
            //    Orderbys = t.Orderbys
            //}).ToListAsync();

            return new PageResult<BTB_CommentdTO> { Data = DATAS, Total = count };
        }

        public async Task<PageResult<BTB_CommentdTO>> GetDataThreeListAsync(PageInput<BTB_Comment> input)
        {
            var put = input.Search;
            //var qs = Db.GetIQueryable<BTB_Comment>()
            //    .Where(t => t.Product_Id.Equals(put.Product_Id) && t.State.Equals(1)).ToList();
            var q = (from a in Db.GetIQueryable<BTB_Comment>().Where(s => s.State.Equals(1))
                     join b in Db.GetIQueryable<Order_Decimal>().Where(t => t.Product_Id.Equals(put.Product_Id)) on a.Product_Id equals b.Id
                     select a);
            if (put.Comment_Image=="Image")
            {
                q = q.Where(t => t.Comment_Image != null);
            }
            q = q.OrderBy(t => t.CreateTime).ThenBy(t => t.Top_Status);
            var count = q.ToList().Count;
            var res = await q.Select(t => new BTB_CommentdTO
            {
                Id = t.Id,
                CreateTime = t.CreateTime,
                Comment_Content = t.Comment_Content,
                _StaffUsers = Db.GetIQueryable<BTB_StaffUser>(true).Where(s => s.id.Equals(t.CreatorId)).Select(s => new BTB_StaffUserDtoTwo { Sex = s.Sex, HeadPortrait = t.IsNickName?"":s.HeadPortrait, id = s.id, NickName = t.IsNickName ? "匿名用户" : s.NickName, HeadType = t.IsNickName ? 0 : s.HeadType }).FirstOrDefault(),
                // CreteName = Db.GetIQueryable<BTB_StaffUser>(true).SingleOrDefault(s => s.id.Equals(t.CreatorId)).NickName,
                Parent_Id = t.Parent_Id,
                Product = Db.GetIQueryable<Order_Decimal>(true).SingleOrDefault(k => k.Id.Equals(t.Product_Id)),
                State = t.State,
                Top_Status = t.Top_Status,
                Orderbys = t.Orderbys,
                Comment_Flag = t.Comment_Flag,
                Comment_State = t.Comment_State,
                Comment_Image = t.Comment_Image,
            }).OrderByDescending(x => x.CreateTime).Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows)
               .ToListAsync();

            //int PeopleCount = q.Where(p => p.Comment_State > 3).Count(); //满意人数
            ////int Counts = q.Count(); //总人数
            //decimal satisfaction = PeopleCount / count;


            var DATAS = GetComment(null, res);
            return new PageResult<BTB_CommentdTO> { Data = DATAS, Total = count };
            ;
        }

        public async Task UpdateDataTwoAsync(List<BTB_CommenTwo> ids)
        {
            for (int i = 0; i < ids.Count; i++)
            {
                var result = await Db.GetIQueryable<BTB_Comment>().SingleOrDefaultAsync(p => p.Id.Equals((ids[i].Id)));
                result.State = ids[i].State;
                await UpdateAsync(result);
            }
        }

        #endregion 外部接口

        #region 私有成员

        private List<BTB_CommentdTO> GetComment(string pid, List<BTB_CommentdTO> _Comments = null)
        {
            var parent = _Comments.Where(P => P.Parent_Id == pid);
            List<BTB_CommentdTO> lists = new List<BTB_CommentdTO>();
            foreach (var item in parent)
            {
                BTB_CommentdTO CommentdChilder = new BTB_CommentdTO();
                CommentdChilder.Id = item.Id;
                CommentdChilder.CreateTime = item.CreateTime;
                CommentdChilder.CreteName = item.CreteName;
                CommentdChilder._StaffUsers = item._StaffUsers;
                CommentdChilder.Product = item.Product;
                CommentdChilder.Product_Id = item.Product_Id;
                CommentdChilder.Comment_Flag = item.Comment_Flag;
                CommentdChilder.Comment_State = item.Comment_State;
                CommentdChilder.Comment_Image = item.Comment_Image;
                CommentdChilder.Parent_Id = item.Parent_Id;
                CommentdChilder.State = item.State;
                CommentdChilder.Comment_Content = item.Comment_Content;

                CommentdChilder._CommentdTOs = GetCommentChildren(CommentdChilder, _Comments);
                lists.Add(CommentdChilder);
            }

            List<BTB_CommentdTO> GetCommentChildren(BTB_CommentdTO bTB, List<BTB_CommentdTO> _CommentdTOs = null)
            {
                if (!_CommentdTOs.Exists(x => x.Parent_Id == bTB?.Id))
                {
                    return null;
                }
                else
                {
                    return GetComment(bTB.Id, _CommentdTOs);
                }
            }
            return lists;
        }

        /// <summary>
        /// 统计
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public BTB_CommentD Getsatisfaction(string Id)
        {

            var q = Db.GetIQueryable<BTB_Comment>()
                .Where(t => t.Product_Id.Equals(Id) && t.State.Equals(1));
            var count = q.ToList().Count;
            int PeopleCount = q.Where(p => p.Comment_State > 3).Count(); //满意人数
            //int Counts = q.Count(); //总人数
            decimal satisfaction = (PeopleCount / count)*100;
            BTB_CommentD _CommentD = new BTB_CommentD
            {
                PeopleCount = PeopleCount,
                satisfaction = satisfaction,
                Count = count

            };


            return _CommentD;
            ;
        }



        #endregion 私有成员
    }
}